package com.ylb.rent.service.impl;

import java.util.List;

import com.xiaoleilu.hutool.util.CollectionUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.ArrayList;

import org.springframework.transaction.annotation.Transactional;
import  com.ylb.rent.entity.City;
 import com.ylb.rent.dao.CountryMapper;
import  com.ylb.rent.entity.Country;
import com.ylb.rent.service.ICountryService;

/**
 * 国家Service业务层处理
 * 
 * @author ylb
 * @date 2023-06-29
 */
@Service
public class CountryServiceImpl implements ICountryService 
{
    @Autowired
    private CountryMapper countryMapper;

    /**
     * 查询国家
     * 
     * @param id 国家主键
     * @return 国家
     */
    @Override
    public Country selectCountryById(Long id)
    {
        return countryMapper.selectCountryById(id);
    }

    /**
     * 查询国家列表
     * 
     * @param country 国家
     * @return 国家
     */

    @Override
    public List<Country> selectCountryList(Country country)
    {
        return countryMapper.selectCountryList(country);
    }

    /**
     * 新增国家
     * 
     * @param country 国家
     * @return 结果
     */
    @Transactional
    @Override
    public int insertCountry(Country country)
    {
        int rows = countryMapper.insertCountry(country);
        insertCity(country);
        return rows;
    }

    /**
     * 修改国家
     * 
     * @param country 国家
     * @return 结果
     */
    @Transactional
    @Override
    public int updateCountry(Country country)
    {
        countryMapper.deleteCityByCountryId(country.getId());
        insertCity(country);
        return countryMapper.updateCountry(country);
    }

    /**
     * 批量删除国家
     * 
     * @param ids 需要删除的国家主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteCountryByIds(Long[] ids)
    {
        countryMapper.deleteCityByCountryIds(ids);
        return countryMapper.deleteCountryByIds(ids);
    }

    /**
     * 删除国家信息
     * 
     * @param id 国家主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteCountryById(Long id)
    {
        countryMapper.deleteCityByCountryId(id);
        return countryMapper.deleteCountryById(id);
    }

    /**
     * 新增城市信息
     * 
     * @param country 国家对象
     */
    public void insertCity(Country country)
    {
        List<City> cityList = country.getCityList();
        Long id = country.getId();
        if (CollectionUtil.isNotEmpty(cityList))
        {
            List<City> list = new ArrayList<City>();
            for (City city : cityList)
            {
                city.setCountryId(id);
                list.add(city);
            }
            if (list.size() > 0)
            {
                countryMapper.batchCity(list);
            }
        }
    }
}
